package com.heima.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.common.PageResponse;
import com.heima.entity.*;
import com.heima.mapper.TbTaskCollectMapper;
import com.heima.mapper.TbTaskMapper;
import com.heima.pojo.vo.TbTaskCollectVo;
import com.heima.pojo.vo.TbTaskVo;
import com.heima.pojo.vo.TbUserVo;
import com.heima.service.ITbTaskCollectService;
import com.heima.service.ITbTaskService;
import com.heima.service.ITbTaskTypeService;
import com.heima.service.ITbUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 工单表 前端控制器
 * </p>
 *
 * @author author
 * @since 2024-06-09
 */
@RestController
@Slf4j
@RequestMapping("/api/task-service")
public class TbTaskController {

    @Autowired
    private ITbTaskService iTbTaskService;

    @Autowired
    private ITbTaskTypeService iTbTaskTypeService;

    @Autowired
    private ITbTaskCollectService iTbTaskCollectService;

    @Autowired
    private TbTaskCollectMapper tbTaskCollectMapper;

    @Autowired
    private ITbUserService iTbUserService;

    @Autowired
    private TbTaskMapper tbTaskMapper;
    @GetMapping("/task/search")
    public PageResponse<TbTaskVo> selectUser(@RequestParam(value = "pageIndex",required = false) Integer pageIndex,
                                             @RequestParam(value = "pageSize",required = false) Integer pageSize,
                                             @RequestParam(value = "innerCode",required = false) String innerCode,
                                             @RequestParam(value = "userId",required = false) Integer userId,
                                             @RequestParam(value = "taskCode",required = false) String taskCode,
                                             @RequestParam(value = "status",required = false) Integer status,
                                             @RequestParam(value = "isRepair",required = false) Boolean isRepair,
                                             @RequestParam(value = "start",required = false) LocalDate start,
                                             @RequestParam(value = "end",required = false) LocalDate end){
        Page<TbTask> page = new Page<>(pageIndex,pageSize);

        //构建查询参数
        QueryWrapper<TbTask> wrapper = new QueryWrapper<>();
        wrapper.lambda().like(innerCode != null,TbTask::getInnerCode,innerCode)
                .like(taskCode != null,TbTask::getTaskCode,taskCode)
                        .eq(userId != null,TbTask::getUserId,userId)
                                .eq(status != null,TbTask::getTaskStatus,status)
                                        .eq(isRepair != false,TbTask::getProductTypeId,isRepair)
                                                .ge(start != null,TbTask::getCreateTime,start)
                                                        .le(end != null,TbTask::getCreateTime,end);
        //执行分页查询
        iTbTaskService.page(page,wrapper);

        List<TbTaskVo> tbTaskVoList = page.getRecords().stream().map(r -> {
            TbTaskVo tbTaskVo = new TbTaskVo();
            Integer typeId = r.getProductTypeId();
            TbTaskType taskType = iTbTaskTypeService.lambdaQuery()
                    .eq(typeId != null, TbTaskType::getTypeId, typeId)
                    .one();

            BeanUtil.copyProperties(r, tbTaskVo);
            tbTaskVo.setTaskType(taskType);
            return tbTaskVo;
        }).collect(Collectors.toList());

        //封装并返回结果
        PageResponse<TbTaskVo> response = new PageResponse<>();
        response.setPageIndex(pageIndex);
        response.setPageSize(pageSize);
        response.setTotalCount((int) page.getTotal());
        response.setCurrentPageRecords(tbTaskVoList);

        return response;
    }
    @GetMapping("/task/taskReportInfo/{start}/{end}")
    public List<TbTaskCollectVo> taskCollects(@PathVariable(value = "start",required = false)
                                                @DateTimeFormat(pattern = "yyyy-MM-dd HH:ss:mm") LocalDateTime start,
                                              @PathVariable(value = "end",required = false)
                                                @DateTimeFormat(pattern = "yyyy-MM-dd HH:ss:mm") LocalDateTime end){
        LocalDate startTime = start.toLocalDate();
        LocalDate endTime = end.toLocalDate();

        List<TbTaskCollect> tbTaskCollects = iTbTaskCollectService.lambdaQuery()
                .ge(start != null, TbTaskCollect::getCollectDate, startTime)
                .le(end != null, TbTaskCollect::getCollectDate, endTime)
                .list();
        List<TbTaskCollectVo> taskCollectVoList = tbTaskCollects.stream().map(tc -> {
            TbTaskCollectVo tbTaskCollectVo = new TbTaskCollectVo();
            Integer total = tc.getCancelCount()+tc.getFinishCount()+tc.getProgressCount();
            log.info("工单总数,{}",total);
            tbTaskCollectVo.setTotal(total);
            tbTaskCollectVo.setCancelTotal(tc.getCancelCount());
            tbTaskCollectVo.setCompletedTotal(tc.getFinishCount());
            tbTaskCollectVo.setProgressTotal(tc.getProgressCount());
            tbTaskCollectVo.setDate(tc.getCollectDate().toString());

            LocalDate date = tc.getCollectDate();
            TbTask tbTask = iTbTaskService.lambdaQuery()
                    .like(date != null, TbTask::getCreateTime, date)
                    .one();
            boolean repair = tbTask.getProductTypeId() == 3 ? true : false;
            tbTaskCollectVo.setRepair(repair);
            Integer userId = tbTask.getUserId();

            Integer workerCount = 0;
            TbUser tbUser = iTbUserService.getById(userId);
            if(tbUser != null){
                workerCount+=1;
            }
            tbTaskCollectVo.setWorkerCount(workerCount);
            return tbTaskCollectVo;
        }).collect(Collectors.toList());

        return taskCollectVoList;
    }
}
